﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;	//Path类用到
using System.Media;    //SoundPlayer命名空间
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using NAudio.Wave;
using System.Diagnostics;

namespace MediaPlayer
{
    public partial class f_MediaPlayer : Form
    {

        private WaveOutEvent outputDevice;
        private AudioFileReader audioFile;


        private bool isDebug = true;

        private int randomPlay = 0;

        public void MessageBox(object omsg)
        {
            string msg =  omsg.ToString();
            if (isDebug) { 
                textBox1.Text += "Debug: " + msg + "\r\n";
                textBox1.SelectionStart = textBox1.Text.Length;//定位光标
                textBox1.ScrollToCaret();//滚动到光标处
            }
            return;
        }
        private System.Timers.Timer atimer;
        public f_MediaPlayer()
        {
            InitializeComponent();


            atimer = new System.Timers.Timer();
            atimer.Elapsed += new ElapsedEventHandler(OnTimeCheck);//注册事件
            atimer.Interval = 1000;
            atimer.AutoReset = true;//设置默认一直执行
            atimer.Enabled = true;//开启计时
            VolBar.Value = 100;
            if (outputDevice != null)
            {
                VolBar.Scroll += (s, a) => outputDevice.Volume = VolBar.Value / 100f;                
            }
            
           



        }

        private void setrdPicBoxImg(int index=0)
        {
            switch (index)
            {
                case 0:
                    rdPicBox.Image = global::MediaPlayer.Properties.Resources.PlaySingle;
                    break;
                case 1:
                    rdPicBox.Image = global::MediaPlayer.Properties.Resources.PlaySingleCircle;
                    break;
                case 2:
                    rdPicBox.Image = global::MediaPlayer.Properties.Resources.PlayInOrder;
                    break;
                case 3:
                    rdPicBox.Image = global::MediaPlayer.Properties.Resources.PlayCircle;
                    break;
                case 4:
                    rdPicBox.Image = global::MediaPlayer.Properties.Resources.PlayRandom;
                    break;
                default:
                    rdPicBox.Image = global::MediaPlayer.Properties.Resources.PlayRandom;
                    break;


            }
            randomPlay = index;
        }

        private void controlPlaylistBox1_Click(object sender, EventArgs e)
        {
            int index = controlPlaylistBox1.SelectedIndex;
            setrdPicBoxImg(index);
            controlPlaylistBox1.Visible = false;
        }


        List<string> listsongs = new List<string>();   //用来存储音乐文件的全路径
        private void b_open_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "请选择音乐文件";//对话框标题
            ofd.InitialDirectory = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//初始目录为程序执行目录
            ofd.Multiselect = true;//设置多选
            ofd.Filter = @"音乐文件|*.mp3||*.wma|所有文件|*.*";//文件格式筛选
            ofd.ShowDialog();//显示对话框
            string[] file_paths = ofd.FileNames;//获得在文件夹中所选择的所有文件的全路径
            for (int i = 0; i < file_paths.Length; i++)
            {
                PlayListBox.Items.Add(Path.GetFileName(file_paths[i]));//将音乐文件的文件名加载到listBox中
                listsongs.Add(file_paths[i]);//将音乐文件的全路径存储到泛型集合中
            }
        }

        //实现双击播放
        SoundPlayer sp = new SoundPlayer();//系统播放器
       


        private void listBox1_DoubleClick(object sender,EventArgs e)
        {
            if (PlayListBox.SelectedItems.Count == 0)//异常处理
            {
                MessageBox("点了空白处，不会播放的");
                return;
            }
            string Path = listsongs[PlayListBox.SelectedIndex];
            toPlay(Path);

        }

        /// <summary>
        /// 上一曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void b_previous_Click(object sender, EventArgs e)
        {
            int index = PlayListBox.SelectedIndex;//获得当前选中歌曲的索引
            index--;
            if (index == PlayListBox.Items.Count)
            {
                index = 0;
            }
            PlayListBox.SelectedIndex = index;//将改变后的索引重新赋值给当前选中项的索引
            toPlay(listsongs[index]);

        }
        /// <summary>
        /// 下一曲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void b_next_Click(object sender, EventArgs e)
        {
            int index = PlayListBox.SelectedIndex;//获得当前选中歌曲的索引
            index++;
            if (index == PlayListBox.Items.Count)
            {
                index = 0;
            }
            PlayListBox.SelectedIndex = index;//将改变后的索引重新赋值给当前选中项的索引
            toPlay(listsongs[index]);

        }
        /// <summary>
        /// 播放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void b_play_Click(object sender, EventArgs e)
        {
            PlayListBox.SelectedIndex = playStatusIndex();
            toPlay(listsongs[PlayListBox.SelectedIndex]);
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void b_stop_Click(object sender, EventArgs e)
        {
            toStop();
        }
        
        private int playStatusIndex()
        {
            int index = 0;
            switch (randomPlay)
            {
                case 0:
                    index = PlayListBox.SelectedIndex;
                    MessageBox("当前单曲播放:第" + index + "首!!");
                    break;
                case 1:
                    index = PlayListBox.SelectedIndex;
                    MessageBox("当前单曲循环:第" + index + "首!!");
                    break;
                case 2:
                    index = PlayListBox.SelectedIndex;
                    index++;
                    if (index == PlayListBox.Items.Count)
                    {
                        index = 0;
                    }
                    MessageBox("当前顺序播放:第" + index + "首!!");
                    break;
                case 3:
                    index = PlayListBox.SelectedIndex;
                    index++;
                    if (index == PlayListBox.Items.Count)
                    {
                        index = 0;
                    }
                    MessageBox("当前列表循环:第" + index + "首!!");
                    break;
                case 4:
                    Random rd = new Random();
                    if (PlayListBox.Items.Count != 1) {
                    index = rd.Next(1, PlayListBox.Items.Count);
                    }
                    MessageBox("当前随机播放:第" + (index+1) + "首!!");
                    break;
                default:
                    break;
            }
            return index;
        }
        /// <summary>
        /// 音量变化
        /// </summary>
        private void VolBar_ValueChanged(object sender,EventArgs e)
        {
            int volNum = VolBar.Value;
            
        }
        /// <summary>
        /// 播放进度条变化事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimeTrackBar_Scroll(object sender,EventArgs e)
        {
            if (audioFile != null && outputDevice!=null)
            {
                outputDevice.Pause();
                
                int processTime = (int)audioFile.TotalTime.TotalSeconds;
                 audioFile.CurrentTime = new TimeSpan(0, (int)((timeTrackBar.Value / 100f) * processTime / 60), (int)((timeTrackBar.Value / 100f) * processTime % 60));

                audioFile.CurrentTime = audioFile.CurrentTime.Add(new TimeSpan(0, timeTrackBar.Value * processTime / 600 , (int)((timeTrackBar.Value * processTime / 100f)  % 60)));

                outputDevice.Play();
                
            }
        }


        private string getCurrentTimes()
        {
            if (audioFile == null) { return null; }
            string time=audioFile.CurrentTime.ToString(@"mm\:ss");
            return time;
        }
        private string getTotalTimes()
        {

            //string time = audioFile.TotalTime.ToString(@"hh\:mm\:ss");
            string time = audioFile.TotalTime.ToString(@"mm\:ss"); ;
            return time;
        }


        private  void OnTimeCheck(object source,EventArgs e)
        {
             string TimeCheck()
            {
                currentTimeLabel.Text = getCurrentTimes();
                if (audioFile != null)
                {
                    int currentTimeProcess = (int)((audioFile.CurrentTime.TotalSeconds / audioFile.TotalTime.TotalSeconds) * 100);
                    if(currentTimeProcess<= timeTrackBar.Maximum)//异常处理
                    {
                        timeTrackBar.Value = currentTimeProcess;
                    }
                    if (audioFile.CurrentTime == audioFile.TotalTime)
                    {
                        toStop();
                        int index = PlayListBox.SelectedIndex;//获得当前选中歌曲的索引
                        index--;
                        if (index == PlayListBox.Items.Count)
                        {
                            index = 0;
                        }
                        PlayListBox.SelectedIndex = index;//将改变后的索引重新赋值给当前选中项的索引
                        toPlay(listsongs[index]);

                    }
                    

                    if (audioFile != null)
                    {

                        MessageBox((timeTrackBar.Value * audioFile.TotalTime.TotalSeconds / 100)  % 60);
                       
                    }

                }
                MessageBox("播放状态:" + randomPlay);
                return null;
            }
            returnInvoke(TimeCheck);
            
        }
        /// <summary>
        /// 开始播放
        /// </summary>
        /// <param name="FileName">文件路径</param>
        private void toPlay(string FileName="")
        {
            toStop();
            if (outputDevice == null)
            {
                outputDevice = new WaveOutEvent();
                
            }
            if (audioFile == null)
            {
                audioFile = new AudioFileReader(listsongs[PlayListBox.SelectedIndex]);
                outputDevice.Init(audioFile);
            }
            outputDevice.Play();

            string currentTime()
            {
                currentTimeLabel.Text = getCurrentTimes();
                return null;
            }
            returnInvoke(currentTime);
            string totalTime()
            {
                TotalTimeLabel.Text = getTotalTimes();
                return null;
            }
            returnInvoke(totalTime);
        }
        /// <summary>
        /// 停止播放
        /// </summary>
        private void toStop()
        {

            if(outputDevice != null)
            {
                outputDevice.Dispose();
                outputDevice = null;
            }
            if (audioFile != null)
            {
                audioFile.Dispose();
                audioFile = null;
            }

            return;
        }

        //建立个委托
        private delegate string returnStrDelegate();
        //判断一下是不是该用Invoke滴~，不是就直接返回~
        private string returnInvoke(returnStrDelegate myDelegate)
        {
            if (this.InvokeRequired)
            {
                return (string)this.Invoke(myDelegate);
            }
            else
            {
                return myDelegate();
            }
        }

        private void rdPicBox_Click(object sender, EventArgs e)
        {
            rdPicBox.Image = Image.FromFile(System.AppDomain.CurrentDomain.BaseDirectory+@"Resources\randomPlay_presspng.png");
            string DirPath = System.AppDomain.CurrentDomain.BaseDirectory;
            controlPlaylistBox1.Visible = true;
            
        }
        private void controlPlaylistBox1_MouseLeave(object sender, EventArgs e)
        {
            controlPlaylistBox1.Visible = false;
        }

        private void controlPlaylistBox1_MouseMove(object sender, MouseEventArgs e)
        {
            controlPlaylistBox1.SelectedIndex = controlPlaylistBox1.IndexFromPoint(e.Location);
        }

        private void b_playSchedule_Click(object sender, EventArgs e)
        {
            ScheduleForm scheduleForm = new ScheduleForm();
            scheduleForm.Show();
        }
    }
}
